//
//  CYYNetWorkManager+User.m
//  LetsPartyBmob
//
//  Created by rimi on 15/9/9.
//  Copyright (c) 2015年 柴阳阳. All rights reserved.
//

#import "CYYNetWorkManager+User.h"

@implementation CYYNetWorkManager (User)

#pragma mark - 用户注册
//注册:参数：姓名，手机号，密码
+ (void)signUpWithName:(NSString *)name
     mobilePhoneNumber:(NSString *)phoneNumber
              password:(NSString *)password
                 email:(NSString *)email
                sucess:(Sucess)sucess
                  fail:(Fail)fail{
    
    BmobUser *bUser = [[BmobUser alloc] init];
//    bUser.password = password;
//    bUser.mobilePhoneNumber = phoneNumber;
    //给username设置: name + date
    //获得当前系统的时间
    NSDate * currentDate = [NSDate date];
    //时间转换成NSString
    NSDateFormatter * dateFormate = [[NSDateFormatter alloc]init];
    [dateFormate setDateFormat:@"yyyy/MM/dd hh:mm"];
    NSString * currentDateString = [dateFormate stringFromDate:currentDate];
    bUser.username = [NSString stringWithFormat:@"%@%@",name,currentDateString];
    [bUser setMobilePhoneNumber:phoneNumber];
    [bUser setPassword:password];
    [bUser setObject:name forKey:@"name"];
    bUser.email = email;
    [bUser signUpInBackgroundWithBlock:^ (BOOL isSuccessful, NSError *error){
        if (isSuccessful){
            sucess(@"注册成功,请尽快激活邮箱!谢谢!");
            [CYYNetWorkManager signOut];
        } else {
            fail(error);
        }
    }];
}

#pragma mark - 用户登陆
//登陆:参数：手机号 + 密码
//每次你登录成功，都会在本地磁盘中有一个缓存的用户对象作为当前用户，可以获取这个缓存的用户对象来进行登录：
+ (void)signInWithmMobilePhoneNumber:(NSString *)phoneNumber
                            password:(NSString *)password
                        sucessSignIn:(SucessSignIn)sucessSignIn
                                fail:(Fail)fail{
    [BmobUser loginInbackgroundWithAccount:phoneNumber andPassword:password block:^(BmobUser *user, NSError *error) {
        if (user) {
//            NSLog(@"%@",user);
            sucessSignIn(user);
        } else {
            fail(error);
        }
    }];
}

#pragma mark - 获得本地缓存的用户信息
//获取当前登陆的用户
//每次你登录成功，都会在本地磁盘中有一个缓存的用户对象作为当前用户，可以获取这个缓存的用户对象来进行登录：
+ (BmobUser *)currentUserGet{
    return [BmobUser getCurrentUser];
}
#pragma mark - 注销登陆：清楚本地缓存的数据
//注销当前登陆
+ (void)signOut{
    [BmobUser logout];
}
#pragma mark - 更新用户资料
//更新姓名
+ (void)usernameChangeWithNewUsername:(NSString *)newUsername
                               sucess:(Sucess)sucess
                                 fail:(Fail)fail{
    BmobUser *user = [BmobUser getCurrentUser];
    [user setObject:newUsername forKey:@"name"];
    [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            sucess(@"姓名更新成功");
        }else{
            fail(error);
        }
    }];
}

//更新手机号
+ (void)mobilePhoneNumberChangeWithNewMobilePhoneNumber:(NSString *)newMobilePhoneNumber
                                                 sucess:(Sucess)sucess
                                                   fail:(Fail)fail{
    BmobUser *user = [BmobUser getCurrentUser];
    user.mobilePhoneNumber = newMobilePhoneNumber;
    [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            sucess(@"手机号更新成功");
        }else{
            fail(error);
        }
    }];
}
//只更新用户名和手机号
+ (void)updateUserInfoWithNewUsername:(NSString *)newUsername
                 newMobilePhoneNumber:(NSString *)newMobilePhoneNumber
                               sucess:(Sucess)sucess
                                 fail:(Fail)fail{
    BmobUser *user = [BmobUser getCurrentUser];
    user.mobilePhoneNumber = newMobilePhoneNumber;
    [user setObject:newUsername forKey:@"name"];
    [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            sucess(@"信息更新成功");
        }else{
            fail(error);
        }
    }];
}


//更新用户所有信息
+ (void)updateUserInfoWithNewUsername:(NSString *)newUsername
                 newMobilePhoneNumber:(NSString *)newMobilePhoneNumber
                     newFirstPassword:(NSString *)newFirstPassword
                    newSecondPassword:(NSString *)newSecondPassword
                               sucess:(Sucess)sucess
                                 fail:(Fail)fail{
    [CYYNetWorkManager passwordChangeWithNewFirstPassword:newFirstPassword newSecondPassword:newSecondPassword sucess:^(NSString *sucessString) {
        //两次密码一样的话进行下一步操作
        BmobUser *user = [BmobUser getCurrentUser];
        user.mobilePhoneNumber = newMobilePhoneNumber;
        [user setObject:newUsername forKey:@"name"];
        [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            if (isSuccessful) {
                sucess(@"信息更新成功");
            }else{
                NSError * error = [[NSError alloc]initWithDomain:@"网络出错" code:1111013 userInfo:nil];
                fail(error);
            }
        }];

    } fail:^(NSError *error) {
        //两次密码不一样
        fail(error);
    }];
}

#pragma mark - 修改密码
//修改密码
+ (void)passwordChangeWithNewFirstPassword:(NSString *)newFirstPassword
                         newSecondPassword:(NSString *)newSecondPassword
                                    sucess:(Sucess)sucess
                                      fail:(Fail)fail{
    BmobUser *user = [BmobUser getCurrentUser];
    
    if ([newFirstPassword isEqualToString:newSecondPassword]) {
        user.password = newSecondPassword;
        [user updateInBackground];
        [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            if (isSuccessful) {
                sucess(@"修改成功");
                //用新密码登录
                [self signInWithmMobilePhoneNumber:user.mobilePhoneNumber password:newSecondPassword sucessSignIn:^(BmobUser *user) {
                    
                } fail:^(NSError *error) {
                    
                }];
            }else{
                fail(error);
            }
        }];
    }else{
        NSError * error = [[NSError alloc]initWithDomain:@"两次输入的密码不一致" code:1231231231 userInfo:nil];
        fail(error);
    }
    
}

#pragma mark - 忘记密码
/**< 第一步 */
+ (void)forgetPasswordWithMobilePhoneNumber:(NSString *)mobilePhoneNumber
                                       name:(NSString *)name
                                     sucess:(SucessCheck)sucess
                                       fail:(Fail)fail{
    //请求该手机号的用户
    BmobQuery * bQuery = [BmobQuery queryForUser];
    [bQuery whereKey:@"mobilePhoneNumber" equalTo:mobilePhoneNumber];
    [bQuery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error) {
            fail(error);
        }else{
            if (array.count == 0) {
                NSError * secError = [[NSError alloc]initWithDomain:@"无此手机号" code:10017043 userInfo:nil];
                fail(secError);
            }else{
                BmobUser * bUser = array[0];
                if ([[bUser objectForKey:@"name"] isEqualToString:name]) {//如果名字相同
                    sucess(@"验证成功",array[0]);
                }else{
                    NSError * error = [[NSError alloc]initWithDomain:@"验证失败" code:10098 userInfo:nil];
                    fail(error);
                }
            }
        }
    }];
}
/**< 第二步 */
//修改密码
+ (void)forgetPasswordSecondChangeWithBmobUser:(BmobUser *)user
                              NewFirstPassword:(NSString *)newFirstPassword
                             newSecondPassword:(NSString *)newSecondPassword
                                        sucess:(Sucess)sucess
                                          fail:(Fail)fail{
    if ([newFirstPassword isEqualToString:newSecondPassword]) {
        user.password = newSecondPassword;
    
        [user updateInBackground];
        [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            if (isSuccessful) {
                sucess(@"修改成功");
            }else{
                fail(error);
            }
        }];
    }else{
        NSError * error = [[NSError alloc]initWithDomain:@"两次输入的密码不一致" code:1231231231 userInfo:nil];
        fail(error);
    }
    
}
//邮箱重置密码
+ (void)changPassworgByEmail:(NSString *)email
                      sucess:(Sucess)sucess
                        fail:(Fail)fail{
    BmobQuery *query = [BmobUser query];
    [query whereKey:@"email" equalTo:email];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error) {
            NSError * cError = [NSError errorWithDomain:@"网络出错,请重试" code:70317112 userInfo:nil];
            fail(cError);
        }else{
            if (array.count > 0 ) {
                sucess(@"邮件发送成功,请尽快登录邮箱修改密码!");
                [BmobUser requestPasswordResetInBackgroundWithEmail:email];
            }else{
                sucess(@"用户不存在");
            }
        }
    }];
}

#pragma mark - 根据用户的ObjectId获得改用户的基本信息
+ (void)getUserDetailInfoWithOnjectId:(NSString *)objectId
                               sucess:(SucessGetUserInfo)sucess
                                 fail:(Fail)fail{
    //查找GameScore表
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"_User" ];
    //查找GameScore表里面id为0c6db13c的数据
    [bquery getObjectInBackgroundWithId:objectId block:^(BmobObject *bUser,NSError *error){
        if(error){
            fail(error);
        }else{
            sucess(bUser);
        }
    }];
}
#pragma mark - 根据用户的ObjectId获得改用户的基本信息《NEW》
+ (void)newGetUserDetailInfoWithOnjectId:(NSString *)objectId
                               sucess:(SucessGetUserInfoDict)sucess
                                 fail:(Fail)fail{
    NSMutableDictionary * userInfoDict = [NSMutableDictionary dictionary];
    //查找GameScore表
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"_User" ];
    //查找GameScore表里面id为0c6db13c的数据
    [bquery getObjectInBackgroundWithId:objectId block:^(BmobObject *bUser,NSError *error){
        if(error){
            fail(error);
        }else{
            userInfoDict[@"objectId"] = bUser.objectId;
            userInfoDict[@"name"] = [bUser objectForKey:@"name"];
            userInfoDict[@"mobilePhoneNumber"] = [bUser objectForKey:@"mobilePhoneNumber"];
            sucess(userInfoDict);
        }
    }];
}


@end
